const headers = { "Content-Type": "application/json" };
const _form = this.pageObj.retrievePlugin('base-forms');
const $form = this.pageObj.getApiWidgetByAliasName('form_14');
const $form144 = this.pageObj.getApiWidgetByAliasName('form_144');
const data = _form.getFormData('form_14');
const equipmentId = data?.id;
const optss = this.pageObj.getApiWidgetsByClassName('opts-form');
const stop = this.pageObj.getApiWidgetByAliasName('stop');
const enums = this.getApiPage().getVariables();
const proxy = getVariable('environmentType');
function basePost(url, body) {
  const option = { method: 'POST', headers, body: JSON.stringify(body) };
  return fetch(url, option).then(res => res.json());
}
function baseGet(url) {
  return fetch(url, { headers }).then(res => res.json());
}

console.log($event);

this.getApiPage().setVariables([{ name: 'optss', value: $event }]);

$form144.hideWidget();
stop.hideWidget();
optss.forEach(v => v.showWidget());

function getVariable(name) {
  if (Array.isArray(enums)) {
    return enums.find(item => item.name === name)?.value;
  }
}

function verifyHKConfig (config, callSecurity = () => {}) {
  if (config?.hkSecurityConfig) {
    return callSecurity
  } else {
    return () => {
      layer?.msg('摄像头尚未添加安放平台配置，请先添加配置！');
      console.error('摄像头尚未添加安放平台配置，请先添加配置！');
    }
  }
}

function selectPlatform(config, callMedia, callSecurity) {
  var platform = getVariable('videoPlatform');
// 3d放大
  if (platform === 'media') {
    // 流媒体
    return callMedia
  } else if (platform === 'security') {
    // 海康安防平台
    return verifyHKConfig(config, callSecurity)
  }
}

function queryPresets(cb = () => {}) {
  return selectPlatform(data.equipmentConfig, () => {
    // 流媒体
    return basePost(
        `/${proxy}IotDdevice/project-business-iot-service/hikvision/sdk/queryPresets`,
        { equipmentId }
    ).then(cb);
  }, () => {
    // 安防平台
    return basePost(
        `/${proxy}IotDdevice/project-business-iot-service/hikvision/sec/${equipmentId}/preset/search`,
        { cameraIndexCode: equipmentId }
    ).then(cb);
  });
}

function queryCruises(cb = () => {}) {
  return selectPlatform(data.equipmentConfig, () => {
    // 流媒体
    return basePost(
        `/${proxy}IotDdevice/project-business-iot-service/hikvision/sdk/queryCruises`,
        { equipmentId }
    ).then(cb);
  }, () => {
    // 安防平台
    return basePost(
        `/${proxy}IotDdevice/project-business-iot-service/hikvision/sec/${equipmentId}/cruiseRoute/search`,
        { cameraIndexCode: equipmentId }
    ).then(cb);
  });
}

function reRenderForm(name, list) {
  $form.widgetObj._option.options = { list };
  this.pageObj.setVariables([{ name, value: list }]);
  $form.widgetObj.render();
  _form.setFormData('form_14', { id: equipmentId })
}


const onClick = () => {
  if (!equipmentId) {
    return layer?.msg('请先选择摄像头');
  }

  switch ($event) {
    case 'preset':
      // 预置位
      queryPresets(({ success, result }) => {
        if (success) {
          const device_list = result.map(v => ({
            ...v,
            sourceName: v.name,
            name: v.presetNum + '-' + v.name,
            value: v.presetNum
          }));
          console.log('_form', _form);
          reRenderForm('device_list', device_list)
        }
      });
      break;
    case 'cruise':
      // 轮询 / 巡航
      queryCruises(({ success, result }) => {
        if (success) {
          console.log('_form', _form);
          const route_list = result.map(v => ({
            ...v,
            name: v.cruiseRoute + '-巡航路径' + v.cruiseRoute,
            value: v.cruiseRoute
          }));
          reRenderForm('route_list', route_list)
        }
      });
      break;
    case 'watchOut':
      // 守望
      optss.forEach(v => v.hideWidget());
      stop.hideWidget();
      $form.showWidget();
      $form144.widgetObj.resetForm('form_144');
      $form144.showWidget();
      queryPresets(({ success, result }) => {
        if (success) {
          const list = result.slice(0, 32);
          $form.widgetObj._option.options = {
            list: list.map(v => ({
              ...v,
              sourceName: v.name,
              name: v.presetNum + '-' + v.name,
              value: v.presetNum
            }))
          };
          $form.widgetObj.render();
          _form.setFormData('form_14', {
            id: equipmentId,
          })
        }
      });

      selectPlatform(data.equipmentConfig, () => {
        // 流媒体
        /**
         * 获取当前的守望
         * 用于在选择时显示当前选中项。
         */
        baseGet(
            `/${proxy}IotDdevice/project-business-iot-service/hikvision/sdk/getParkAction?equipmentId=${equipmentId}`
        ).then(({ success, result }) => {
          if(success) {
            this.pageObj.setVariables([
              {name: 'watchOut', value: {time: result.parkTime, id: result.id}}
            ])
          }
        });
      }, () => {
        // 安防平台
        window.layer?.msg('暂不支持守望!')
      });

      break;
  }
}

onClick ()